import Vuex from 'vuex';
import Vue from 'vue';
import axios from 'axios'

Vue.use(Vuex);

const actions = {
    incrementIfOdd(miniStore, value) {
        if (state.sum % 2) {
            miniStore.commit('INCREMENT_IF_ODD', value)
        }
    },
    incrementWait(miniStore, value) {
        setTimeout(() => {
            miniStore.commit('INCREMENT_WAIT', value)
        }, 500)
    },
    incrementServer() {
        axios.get('https://api.uixsj.cn/hitokoto/get?type=soup').then(
            response => {
                miniStore.commit('INCREMENT_SERVER', response.data.length)
            },
            err => {
                alert(err)
            }
        )
    },

}

const mutations = {
    INCREMENT(state, value) {
        state.sum += value
    },
    DECREMENT(state, value) {
        state.sum -= value
    },
    INCREMENT_IF_ODD(state, value) {
        state.sum += value
    },
    INCREMENT_WAIT(state, value) {
        state.sum += value
    },
    INCREMENT_SERVER(state, value) {
        state.sum += value
    }
}

const getters = {
    bigSum(state) {
        const big = state.sum * 10;
        return big;
    },
    smallDescription(state) {
        const small = state.description.slice(0, 3);
        return small;
    }
}

const state = {
    sum: 0,
    description: '一个简单的求和组件，只能加和减'
}

export default new Vuex.Store({
    actions,
    mutations,
    getters,
    state
})